package cn.com.guage.transtation.service;

import cn.com.guage.transtation.dao.TccAccountDao;
import cn.com.guage.transtation.dao.TccTransactionDao;
import cn.com.guage.transtation.entity.TccAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TccTransferService {
    @Autowired
    private TccAccountDao accountDao;
    @Autowired
    private TccTransactionDao transactionDao;

    @Transactional
    public boolean tryTransfer(String txId, Long fromId, Long toId, int amount) {
        Integer status = transactionDao.getTransactionStatus(txId);
        if (status != null) return status == 1;

        TccAccount fromAccount = accountDao.selectForUpdate(fromId);
        TccAccount toAccount = accountDao.selectForUpdate(toId);

        if (fromAccount.getBalance() < amount) return false;

        fromAccount.setBalance(fromAccount.getBalance() - amount);
        fromAccount.setFrozen(fromAccount.getFrozen() + amount);
        if (!accountDao.updateAccount(fromAccount)) throw new RuntimeException("Try失败");

        transactionDao.insertTransaction(txId, 0);
        return true;
    }

    @Transactional
    public boolean confirmTransfer(String txId, Long fromId, Long toId, int amount) {
        Integer status = transactionDao.getTransactionStatus(txId);
        if (status == null) throw new RuntimeException("事务不存在");
        if (status == 1) return true;

        TccAccount fromAccount = accountDao.selectForUpdate(fromId);
        TccAccount toAccount = accountDao.selectForUpdate(toId);

        fromAccount.setFrozen(fromAccount.getFrozen() - amount);
        toAccount.setBalance(toAccount.getBalance() + amount);
        if (!accountDao.updateAccount(fromAccount) || !accountDao.updateAccount(toAccount)) {
            throw new RuntimeException("Confirm失败");
        }

        transactionDao.insertTransaction(txId, 1);
        return true;
    }

    @Transactional
    public boolean cancelTransfer(String txId, Long fromId, Long toId, int amount) {
        Integer status = transactionDao.getTransactionStatus(txId);
        if (status == null) throw new RuntimeException("事务不存在");
        if (status == 2) return true;

        TccAccount fromAccount = accountDao.selectForUpdate(fromId);
        fromAccount.setBalance(fromAccount.getBalance() + amount);
        fromAccount.setFrozen(fromAccount.getFrozen() - amount);
        if (!accountDao.updateAccount(fromAccount)) throw new RuntimeException("Cancel失败");

        transactionDao.insertTransaction(txId, 2);
        return true;
    }
}